from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import os

# https://googlechromelabs.github.io/chrome-for-testing/
# https://storage.googleapis.com/chrome-for-testing-public/128.0.6613.86/mac-arm64/chromedriver-mac-arm64.zip
# 获取无头浏览器实例 @2024-05-30

class WebDriverInstance:
    _instance = None
    def get_driver(self):
        return self._instance

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(WebDriverInstance, cls).__new__(cls)
        return cls._instance

    def __init__(self):
        if not hasattr(self, 'initialized'):
            self.initialized = True
            ## /usr/bin/chromium
            # 替换为你的ChromeDriver路径
            chrome_driver_path = os.getenv('CHROME_DRIVER', '/Users/alexxiao/src/chromedriver-mac-arm64/chromedriver')
            # 配置 Chrome 选项为无头模式
            chrome_options = Options()
            chrome_options.add_argument('--headless')
            chrome_options.add_argument('--disable-gpu')

            # 创建 ChromeDriver 服务
            service = Service(chrome_driver_path)
            # 初始化 ChromeDriver
            self._instance = webdriver.Chrome(service=service, options=chrome_options)
